package com.levi.utils.log.printer;


import com.levi.utils.log.formatter.Decorator;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Levi on 2018/3/13.
 */
public abstract class Printer {

    private final List<Decorator> mDecorators = new ArrayList<>();

    public Printer addDecorator(Decorator decorator) {
        mDecorators.add(decorator);
        return this;
    }

    public boolean isLoggable(String tag, int priority) {
        return true;
    }

    public void log(final int priority, final String tag, String msg, Throwable throwable) {
        if (!isLoggable(tag, priority)) {
            return;
        }
        String printMsg = msg;
        for (Decorator decorator : mDecorators) {
            printMsg = decorator.decorate(printMsg);
        }
        if (printMsg == null) {
            printMsg = "";
        }
        if (throwable != null) {
            printMsg += "\n" + getStackTraceString(throwable);
        }
        log(priority, tag, printMsg);
    }

    private String getStackTraceString(Throwable throwable) {
        // Don't replace this with Log.getStackTraceString() - it hides
        // UnknownHostException, which is not what we want.
        final StringWriter sw = new StringWriter(256);
        final PrintWriter pw = new PrintWriter(sw, false);
        throwable.printStackTrace(pw);
        pw.flush();
        return sw.toString();
    }

    public abstract void log(int priority, String tag, String msg);
}
